package main

import (
	"context"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

/**
拓展部分 - 优雅关停
*/
func main() {
	r := gin.Default()

	r.GET("/test", func(c *gin.Context) {
		time.Sleep(10 * time.Second)
		c.String(http.StatusOK, "hello test")
	})

	srv := &http.Server{
		Addr:    ":8080",
		Handler: r,
	}

	go func() {
		// 启动服务，获取返回信息
		// 如果返回错误不为nil，且返回结果不为服务关闭
		err := srv.ListenAndServe()
		if err != nil && err != http.ErrServerClosed {
			log.Fatal("listen: %s\n", err)
		}

		if err == nil {
			log.Printf("server run !!!")
		}
	}()

	quit := make(chan os.Signal)

	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	// 阻塞线程
	<-quit
	// 输出日志
	log.Print("server shutdown")

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatalf("server shutdown:", err)
	}

	log.Printf("server exiting")

	/**
	取消阻塞方式
	*/
	//r.Run()
}
